import Taro, { Component, useState } from '@tarojs/taro';
import { View, Icon, Navigator, Image, Text, Picker } from '@tarojs/components';
import NavigationBar from '../../../components/navigationBar/index';

import Next from '../../static/user/icon_next.png';
import IconBorder from '../../../static/home/shopc.png';
import { ShoppingCartlist, ShoppingCartpurchase, ShoppingCartEdit, ShoppingCartdel } from '../../../services/goods';
import { fullImgUrl, timeFormat } from '../../../utils/utils';
import discount from './img/discount.png';
import del from './img/del.png';
import del1 from './img/del1.png';
import add from './img/add.png';
import selected from './img/selected.png';

import fselected from './img/fselected.png';


import './index.scss';
import { updateNickname } from '../../../services/user';

export default class Index extends Component {
  config = {
    navigationBarTitleText: '购物车'
  }

  state = {
    navigationBarTitleText: '购物',
    animation: '',

    startX: 0, //开始坐标
    startY: 0,
    carts: [
      // {
      //   id: 1,
      //   title: '好喝⾼颜值MEOW莫斯卡托',
      //   image:
      //     'https://tva1.sinaimg.cn/large/00831rSTgy1gczok56tkzj30m80m8qe4.jpg',
      //   num: 3,
      //   price: '88.00',
      //   selected: true
      // },
      // {
      //   id: 2,
      //   title: '好喝⾼颜值MEOW莫斯卡托',
      //   image:
      //     'https://tva1.sinaimg.cn/large/00831rSTgy1gczok56tkzj30m80m8qe4.jpg',
      //   num: 3,
      //   price: '88.00',
      //   selected: true
      // },
    ], // 购物车列表
    hascheckList: [],
    member_level: Taro.getStorageSync('userInfo').member_level,
    deliveryTime: '',
    startDeliveryTime: '',
    balance: Taro.getStorageSync('userInfo').balance,
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
    totalPrice: 0, // 总价，初始为0
    totalBalance: 0, // 总优惠金额，初始0
    selectAllStatus: true // 全选状态，默认全选
  }

  componentDidShow() {
    let animation = Taro.createAnimation({
      duration: 400,
      timingFunction: 'linear',
      delay: 100,
      transformOrigin: 'left top 0',
      success: function (res) {
        console.log(res)
      }
    })

    // this.setState({
    //   animation: animation
    // })
    ShoppingCartlist({
    }).then(res => {
      res.list.forEach((item, index) => {
        item.has_sku[0].fish_cover = fullImgUrl(item.has_sku[0].fish_cover)
        item.has_sku[0].card_cover = fullImgUrl(item.has_sku[0].card_cover)

        item.animation = animation
        if (item.status == 1) {
          item.selected = false

        } else {
          item.selected = true

        }
      })
      // setTimeout(() => {
      this.setState({
        carts: res.list
      })
      // if()

      // }, 2000);

    })
    let date = new Date();
    date.setDate(date.getDate() + 1);
    // 下午三点半以后，后天再发货
    if (date.getHours() > 15 || (date.getHours() === 15 && date.getMinutes() >= 30)) {
      date.setDate(date.getDate() + 1);
    }
    this.setState({
      startDeliveryTime: timeFormat(parseInt(date.getTime() / 1000, 10), 'yyyy-MM-dd')
    })
  }
  componentDidUpdate() {
    this.getTotalPrice();

  }

  // 滑动开始
  touchstart(e) {
    this.setState({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
    })
  }

  //滑动事件处理 _index当前索引
  touchmove(e) {
    console.log(e)
    var that = this;
    var startX = that.state.startX;//开始X坐标
    var startY = that.state.startY;//开始Y坐标
    var touchMoveX = e.changedTouches[0].clientX;//滑动变化坐标
    var touchMoveY = e.changedTouches[0].clientY;//滑动变化坐标
    // var isLeft = _class.indexOf("leftMove") != -1; //往左滑的位置
    // var isRight = _class.indexOf("rightMove") != -1;//往右滑的位置

    //获取滑动角度
    var angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    //滑动超过30度角 return
    if (Math.abs(angle) > 30) return;
    //右滑
    if (touchMoveX > startX) {
      console.log('右滑');
      //实例化一个动画
      let _animation = Taro.createAnimation({
        duration: 400,
        timingFunction: 'linear',
        delay: 100,
        transformOrigin: 'left top 0',
        success: function (res) {
          console.log(res)
        }
      })

      _animation.translateX(0).step()
      const index = e.currentTarget.dataset.index
      that.state.carts.forEach((ele, i) => {
        if (ele.id == index) {
          that.state.carts[i].animation = _animation.export()
        }
      })
    } else if (touchMoveX - startX < -10) {//左滑
      console.log('左滑');
      //实例化一个动画
      let _animation = Taro.createAnimation({
        duration: 400,
        timingFunction: 'linear',
        delay: 100,
        transformOrigin: 'left top 0',
        success: function (res) {
          console.log(res)
        }
      })

      _animation.translateX(-40).step()
      const index = e.currentTarget.dataset.index
      console.log(index)
      that.state.carts.forEach((ele, i) => {
        if (ele.id == index) {
          that.state.carts[i].animation = _animation.export()
        }
      })
      // that.setState({
      //   //输出动画
      //   carts[index].animation: 
      // })
    }
  }

  /**
    * 计算滑动角度
    * @param {Object} start 起点坐标
    * @param {Object} end 终点坐标
    */
  angle(start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  }


  dateChange(e) {
    if (e.detail.value == '2021-02-11' || e.detail.value == '2021-02-12' || e.detail.value == '2021-02-13') {
      Taro.showToast({
        title: '春节期间不发货,请重新选择发货时间!',
        icon: 'none'
      });

    } else {
      let temp = e.detail.value.split('-');
      this.setState({
        deliveryTime: `${temp[0]}年${temp[1]}月${temp[2]}日`
      })
    }

  }
  /**
 * 计算总价
 */
  getTotalPrice() {
    let carts = this.state.carts;
    let total = 0
    let balance = 0
    let total1 = 0
    let total2 = 0
    for (let i = 0; i < carts.length; i++) {
      // 循环列表得到每个数据
      if (carts[i].selected) {
        // 判断选中才会计算价格
        if (carts[i].member_type == 1) {
          total1 += carts[i].number * carts[i].has_sku[0].price * carts[i].has_goods.discount / 100 // 所有价格加起来
        } else {
          total2 += carts[i].number * carts[i].has_sku[0].price // 所有价格加起来
        }
        if (this.state.member_level == 1) {
          balance += carts[i].has_sku[0].offset_price * carts[i].number

        } else if (this.state.member_level == 2) {
          balance += carts[i].has_sku[0].two_offset_price * carts[i].number

        }
      }
    }
    total = total1 + total2
    var price = Math.round((parseFloat(total.toFixed(2)) - parseFloat(balance.toFixed(2))) * 100) / 100
    if (Math.round((parseFloat(total.toFixed(2)) - parseFloat(balance.toFixed(2))) * 100) / 100 >= 0) {
      var price = Math.round((parseFloat(total.toFixed(2)) - parseFloat(balance.toFixed(2))) * 100) / 100

    } else {
      var price = 0
    }
    this.setState({
      // 最后赋值到data中渲染到页面
      totalPrice: price,
      totalBalance: parseFloat(balance.toFixed(2))
    })
  }


  /**
   * 绑定加数量事件
   */
  addCount(e) {
    const index = e.currentTarget.dataset.index
    console.log(index)
    let carts = this.state.carts
    console.log(carts)
    let num = carts[index].number
    num = num + 1
    carts[index].number = num
    this.setState({
      carts: carts
    })
    this.getTotalPrice()
  }

  /**
   * 绑定减数量事件
   */
  minusCount(e) {
    console.log(e)
    const index = e.currentTarget.dataset.index
    let carts = this.state.carts
    let num = carts[index].number
    if (num <= 1) {
      return false
    }
    num = num - 1
    carts[index].number = num
    this.setState({
      carts: carts
    })
    this.getTotalPrice()
  }

  /**
 * 删除购物车当前商品
 */
  deleteList(item, index) {
    let carts = this.state.carts
    let that = this
    Taro.showModal({
      title: '提示',
      content: '你确定删除这个商品吗',
      success: function (res) {
        if (res.confirm) {
          ShoppingCartdel({
            cart_id: item.id
          }).then(res => {
            let _animation = Taro.createAnimation({
              duration: 400,
              timingFunction: 'linear',
              delay: 1,
              transformOrigin: 'left top 0',
              success: function (res) {
                console.log(res)
              }
            })
            _animation.translateX(0).step()
            carts[index].animation = _animation.export()
            setTimeout(() => {
              carts.splice(index, 1)
            }, 500);
            that.setState({
              carts: carts
            });
            // let _animation = Taro.createAnimation({
            //   duration: 400,
            //   timingFunction: 'linear',
            //   delay: 100,
            //   transformOrigin: 'left top 0',
            //   success: function (res) {
            //     console.log(res)
            //   }
            // })

            // _animation.translateX(0).step()
            // that.state.carts = carts

            // that.state.carts.forEach(ele=>{
            //   ele.animation =_animation.export()
            // })
            // that.state.carts[index].animation = _animation.export()
            // console.log(that..carts)
            if (!carts.length) {
            } else {
              that.getTotalPrice()
            }
          })
        }
      }
    })

  }

  /**
  * 当前商品选中事件
  */
  selectList(id, e) {
    const index = e.currentTarget.dataset.index
    let carts = this.state.carts
    // const selected = carts[index].selected
    // carts[index].selected = !selected

    carts.forEach(item => {
      if (id == item.id) {
        item.selected = !item.selected
      }
    })
    // const checkall = this.data.selectAllStatus === true ? false : false
    this.setState({
      carts: carts,
      // selectAllStatus: false
    })

    const selectAllStatus = carts.every(item => item.selected)
    this.setState({
      selectAllStatus: selectAllStatus
    })
    this.getTotalPrice()
  }
  delcart(item) {
    console.log(item)

  }
  /**
   * 购物车全选事件
   */
  selectAll(e) {
    let selectAllStatus = this.state.selectAllStatus
    selectAllStatus = !selectAllStatus
    let carts = this.state.carts

    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus
    }
    this.setState({
      selectAllStatus: selectAllStatus,
      carts: carts
    })
    this.getTotalPrice()
  }

  // 结算
  closeFun() {
    let list = []
    let listTotal = []
    this.state.carts.map((v, k) => {
      if (v.select) {
        list.push(v)
      } else {
        listTotal.push(v)
      }
    })
  }
  goback() {
    Taro.navigateBack();

  }
  shopgopurchase() {
    var arr = []
    var arredit = []
    this.state.carts.forEach(ele => {
      if (ele.selected == true) {
        arr.push(ele.id)
        arredit.push({
          id: ele.id,
          num: ele.number,
          status: 2
        })
      } else {
        arredit.push({
          id: ele.id,
          num: ele.number,
          status: 1
        })
      }
    })
    if (!this.state.deliveryTime) {
      Taro.showToast({
        title: '请选择发货时间!',
        icon: 'none'
      });
    } else {
      if (arr.length > 0) {
        ShoppingCartEdit({
          ...arredit
        }).then(res => {
          Taro.navigateTo({
            url: `/subPacKagebWork/pages/settlement-center/index?cart_ids=${arr}`
          })
          Taro.setStorageSync('cart_ids', arr);
          Taro.setStorageSync('deliveryTime', this.state.deliveryTime);
        });

      } else {
        Taro.showToast({
          title: '请选择商品!',
          icon: 'none'
        });
      }
    }
  }

  render() {
    const { carts, selectAllStatus, totalPrice, totalBalance, hasList, member_level } = this.state;
    let count = 0;
    carts.map(it => {
      if (it.selected === true) {
        count++;
      }
    })
    return (
      <View className='goods-carts-list' style={`margin-top: ${navigationBarHeight}`}>
        <NavigationBar text="购物车" type="activity" />
        <View className="main">
          {carts.length > 0 ? (
            <View>
              <View className="cart-box">
                <View className="cart-box-top" style="display:flex">
                  <Image className="cart-thumb-shop" src={IconBorder}></Image>
                  <View className="top-title">
                    中鹿岛
                  </View>
                </View>
                {carts.map((item, index) => {
                  return (

                    <View >

                      {/* 每一项 */}
                      <View className='historyItem'>
                        {/* 删除 */}
                        <View onClick={() => { this.deleteList(item, index) }} className='itemDelete right'>删除</View>

                        {/* 遮盖层 */}
                        <View className='itemCover' onTouchStart={this.touchstart.bind(this)} onTouchEnd={this.touchmove.bind(this)} animation={item.animation} data-index={item.id}>
                          {item.selected ? (
                            <Image data-index={index} className="cart-pro-select" onClick={this.selectList.bind(this, item.id)} src={
                              fselected
                            }></Image>

                          ) : (
                            <Image data-index={index} className="cart-pro-select" onClick={this.selectList.bind(this, item.id)} src={
                              selected
                            }></Image>
                          )}
                          <Image className="cart-pro-del" src={
                            del1
                          } onClick={() => { this.deleteList(item, index) }}></Image>
                          <Navigator url={'../details/details?id=' + item.id}>
                            {item.goods_type == 0 ? (
                              <Image className="cart-thumb" src={item.has_sku[0].fish_cover}></Image>
                            ) : (
                              <Image className="cart-thumb" src={item.has_sku[0].card_cover}></Image>
                            )}
                          </Navigator>
                          <Text className="cart-pro-name1">{item.has_sku[0].attr_str}·{item.has_sku[0].goods_name}</Text>
                          {item.member_type == 1 ? (
                            <View className="cart-pro-name2">{'原价￥' + item.has_sku[0].price}</View>

                          ) : (
                            ''
                          )}

                          <View className="goods-footer">
                            {item.member_type == 1 ? (
                              <Text className="footer-pro-price">{'￥' + ((item.has_sku[0].price * item.has_goods.discount) / 100).toFixed(2)}</Text>
                            ) : (
                              <Text className="footer-pro-price">{'￥' + item.has_sku[0].price}</Text>
                            )}
                            <View className="cart-count-box">
                              <Image data-index={index} className="cart-count-add" onClick={this.addCount} src={add}></Image>
                              <Text className="cart-count-num">{item.number}</Text>
                              <Image data-index={index} className="cart-count-down" onClick={this.minusCount} src={del}></Image>
                            </View>
                          </View>
                        </View>
                      </View>

                      {item.member_type == 1 ? (
                        <View className="diyong">
                          <View style="display:flex">
                            <Image className="cart-thumb-discount" src={discount}></Image>
                            <View className="top-title1">抵用券</View>
                          </View>
                          {member_level == 1 ? (

                            <View className="top-title2">已抵用￥{(item.number * item.has_sku[0].offset_price).toFixed(2)}</View>
                          ) : (
                            ''
                          )}
                          {member_level == 2 ? (

                            <View className="top-title2">已抵用￥{(item.number * item.has_sku[0].two_offset_price).toFixed(2)}</View>
                          ) : (
                            ''
                          )}
                        </View>
                      ) : (
                        ''
                      )}

                      <View className="top-line"></View>
                      {/* <Text
                      className="cart-del"
                      onClick={this.deleteList}
                      data-index={index}
                    >
                      删除
                    </Text> */}
                    </View>
                  )
                })}
              </View>
              <View className="chunk">
                <View className="content">
                  <View className="layout1">
                    <Picker className="date-picker" value={deliveryTime} mode='date' start={startDeliveryTime} onChange={this.dateChange}>
                      <View className="wrap">
                        <View className="text-tiem">发货时间</View>
                        <View className="time-number">{deliveryTime}
                          {
                            deliveryTime == '' ? (
                              <View className="text-tiem1">选择时间</View>
                            ) : <View></View>
                          } ></View>
                      </View>
                    </Picker>
                  </View>
                </View>
              </View>
            </View>
          ) : (
            <View>
              <View className="cart-no-data">购物车是空的哦</View>
              <View className="cart-no-data">赶快去下单吧~</View>

              <View className="cart-no-data1" onClick={() =>
                this.goback()
              }>去逛逛</View>
            </View>
          )}
        </View>
        <View className="commonfooter">
          <View style='display:flex;align-items: center;'>
            <View className="bigmoneyFu">￥</View>
            <View className="bigmoney" > {totalPrice}</View>
            <View className="shuoming" >已优惠</View>
            <View className="lastMoney">￥{totalBalance}</View>
          </View>
          <View onClick={this.shopgopurchase} className="wechart">去结算</View>
        </View>
      </View>
    )
  }
}

